<template>
  <div class="login-modal" @click.self="handleClose">
    <div class="login-container">
      <el-card class="card">
        <div class="close-btn" @click="handleClose">
          <el-icon><Close /></el-icon>
        </div>
        <el-tabs v-model="activeTab" stretch>
          <!-- 学生登录 -->
          <el-tab-pane label="学生登录" name="studentLogin">
           <el-form :model="studentLoginForm">
  <el-form-item label="用户名">
    <el-input v-model="studentLoginForm.username" placeholder="请输入用户名" />
  </el-form-item>
  <el-form-item label="学号">
    <el-input v-model="studentLoginForm.studentId" placeholder="请输入学号" />
  </el-form-item>
  <el-form-item label="年级">
    <el-select v-model="studentLoginForm.gradeYear" placeholder="请选择年级">
      <el-option label="研一" :value="1" />
      <el-option label="研二" :value="2" />
      <el-option label="研三" :value="3" />
    </el-select>
  </el-form-item>
  <el-form-item label="密码">
    <el-input v-model="studentLoginForm.password" type="password" placeholder="请输入密码" />
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="handleLogin('student')">登录</el-button>
    <el-button type="text" @click="activeTab = 'register'">注册</el-button>
  </el-form-item>
</el-form>

          </el-tab-pane>

          <!-- 管理员登录 -->
          <el-tab-pane label="管理员登录" name="adminLogin">
            <el-form :model="adminLoginForm">
  <el-form-item label="用户名">
    <el-input v-model="adminLoginForm.username" placeholder="请输入用户名" />
  </el-form-item>
  <el-form-item label="密码">
    <el-input v-model="adminLoginForm.password" type="password" placeholder="请输入密码" />
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="handleLogin('admin')">登录</el-button>
  </el-form-item>
</el-form>

          </el-tab-pane>

          <!-- 学生注册 -->
          <el-tab-pane label="学生注册" name="register">
            <el-form :model="registerForm">
              <el-form-item label="用户名">
                <el-input v-model="registerForm.username" placeholder="设置登录用户名" />
              </el-form-item>
              <el-form-item label="密码">
                <el-input v-model="registerForm.password" type="password" placeholder="设置密码" />
              </el-form-item>
              <el-form-item label="确认密码">
                <el-input v-model="registerForm.confirmPassword" type="password" placeholder="再次输入密码" />
              </el-form-item>
              <el-form-item label="学号">
                <el-input v-model="registerForm.studentId" placeholder="请输入学号" />
              </el-form-item>
              <el-form-item label="学院">
                <el-input v-model="registerForm.college" placeholder="请输入学院" />
              </el-form-item>
              <el-form-item label="专业">
                <el-input v-model="registerForm.department" placeholder="请输入专业" />
              </el-form-item>
              <el-form-item label="姓名">
                <el-input v-model="registerForm.name" placeholder="请输入姓名" />
              </el-form-item>
              <el-form-item label="性别">
                <el-select v-model="registerForm.gender" placeholder="选择性别">
                  <el-option label="男" value="M" />
                  <el-option label="女" value="F" />
                </el-select>
              </el-form-item>
              <el-form-item label="年级">
                <el-select v-model="registerForm.gradeYear" placeholder="选择年级">
                  <el-option label="研一" value="1" />
                  <el-option label="研二" value="2" />
                  <el-option label="研三" value="3" />
                </el-select>
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="registerForm.status" placeholder="选择状态">
                  <el-option label="在读" value="在读" />
                  <el-option label="休学" value="休学" />
                  <el-option label="毕业" value="毕业" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleRegister">注册</el-button>
                <el-button type="text" @click="activeTab = 'studentLogin'">返回登录</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ElIcon, ElMessage } from 'element-plus'
import { Close } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: "LogIn",
  components: { ElIcon, Close },
  emits: ['close'],
  data() {
    return {
      activeTab: "studentLogin",
      studentLoginForm: {
        username: "",
        studentId: "",
        gradeYear: null,
        password: "",
      },
      adminLoginForm: {
        username: "",
        password: "",
      },
      registerForm: {
        username: "",
        password: "",
        confirmPassword: "",
        studentId: "",
        college: "",
        department: "",
        name: "",
        gender: "M",
        gradeYear: null,
        status: null,
      },
    };
  },
  methods: {
    handleClose() {
      this.$emit('close');
    },

    async handleLogin(role) {
      let loginPayload;

      if (role === 'student') {
        const { username, studentId, gradeYear, password } = this.studentLoginForm;
        if (!username || !studentId || !gradeYear || !password) {
          ElMessage.error("用户名、学号、年级和密码都不能为空");
          return;
        }
        loginPayload = {
          username: username.trim(),
          studentId: studentId.trim(),
          gradeYear,
          password: password.trim(),
          role,
        };
      } else if (role === 'admin') {
        const { username, password } = this.adminLoginForm;
        if (!username || !password) {
          ElMessage.error("请输入用户名和密码");
          return;
        }
        loginPayload = {
          username: username.trim(),
          password: password.trim(),
          role,
        };
      }

      try {
        const res = await axios.post("/api/user/login", loginPayload, {
          headers: { "Content-Type": "application/json" },
          withCredentials: true,
        });

        if (res.data.code === 200 && res.data.data) {
          ElMessage.success(res.data.message || "登录成功");

          const { userId, studentId, gradeYear, name, college, department, gender, status, username } = res.data.data;
          localStorage.setItem("userId", userId);

          if (role === "student") {
            // 存储学生完整信息
            localStorage.setItem("studentId", studentId);
            localStorage.setItem("gradeYear", gradeYear);
            localStorage.setItem("studentName", name);
            localStorage.setItem("college", college);
            localStorage.setItem("department", department);
            localStorage.setItem("gender", gender);
            localStorage.setItem("status", status);
            localStorage.setItem("username", username);
            
            // 将完整的学生信息对象存储到localStorage
            const studentInfo = {
              userId,
              studentId,
              gradeYear,
              name,
              college,
              department,
              gender,
              status,
              username
            };
            localStorage.setItem("studentInfo", JSON.stringify(studentInfo));
            
            this.$router.push("/fst/stu");
          } else {
            this.$router.push("/admin");
          }
        } else {
          ElMessage.error(res.data.message || "用户名或密码错误");
        }
      } catch (error) {
        console.error("登录失败", error);
        ElMessage.error("登录失败，请稍后重试");
      }
    },

    async handleRegister() {
      const {
        username,
        password,
        confirmPassword,
        studentId,
        college,
        department,
        name,
        gradeYear,
        status,
      } = this.registerForm;

      if (
        !username || !password || !studentId ||
        !college || !department || !name || !gradeYear || !status
      ) {
        ElMessage.error("请填写所有必填字段");
        return;
      }

      if (!/^[a-zA-Z0-9]{1,15}$/.test(username)) {
        ElMessage.error("用户名只能包含数字和字母，且长度不超过15位");
        return;
      }

      if (!/^\d+$/.test(studentId)) {
        ElMessage.error("学号含非法字符");
        return;
      }

      const chineseReg = /^[\u4e00-\u9fa5]+$/;
      if (!chineseReg.test(college) || !chineseReg.test(department) || !chineseReg.test(name)) {
        ElMessage.error("学院、专业或姓名含非法字符");
        return;
      }

      if (
        !(password.length > 5 && password.length < 15) ||
        !/^[\w\d!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]+$/.test(password)
      ) {
        ElMessage.error("密码格式非法");
        return;
      }

      if (password !== confirmPassword) {
        ElMessage.error("两次密码不一致");
        return;
      }

      try {
        const res = await axios.post("/api/user/register", {
          username: username.trim(),
          password: password.trim(),
          studentId,
          name,
          gender: this.registerForm.gender,
          college,
          department,
          gradeYear,
          status,
        }, {
          headers: { "Content-Type": "application/json" },
          withCredentials: true,
        });

        if (res.data === "注册成功") {
          ElMessage.success("注册成功，请登录");
          this.activeTab = "studentLogin";
        } else {
          ElMessage.error(res.data.message || "注册失败");
        }
      } catch (error) {
        console.error("注册失败", error);
        ElMessage.error("注册失败，请稍后重试");
      }
    },
  },
};
</script>



<style scoped>
.login-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.login-container {
  position: relative;
  width: 400px;
}

.card {
  padding: 30px;
  background: white;
  border-radius: 10px;
  position: relative;
}

.close-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
  z-index: 10;
  font-size: 18px;
  color: #666;
}

.close-btn:hover {
  color: #333;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
